package com.chant.startFarming.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.chant.startFarming.dto.UserDTO;
import com.chant.startFarming.entity.Users;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.chant.startFarming.utils.RedisConstants.LOGIN_USER_TTL;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;
    private ObjectMapper objectMapper;

    public AuthInterceptor(StringRedisTemplate stringRedisTemplate, ObjectMapper objectMapper) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.objectMapper = objectMapper;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从请求头中获取token
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            return true;
        }
        // 2.基于token 从Redis 中获取用户信息
        String key = RedisConstants.LOGIN_USER_KEY + token;
        String userJson = stringRedisTemplate.opsForValue().get(key);

        // 3.判断用户是否存在
        if (StrUtil.isBlank(userJson)) {
            return true; // 没有用户信息，放行（可能是登录请求）
        }
        // 4.将查询到的数据转为UserDTO对象
        UserDTO userDTO = null;
        try {
            userDTO = objectMapper.readValue(userJson, UserDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理转换失败的情况
        }

        if (userDTO == null) {
            return true; // 转换失败，放行
        }

        // 6.存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        // 7.刷新token的有效期
        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}